﻿using CommonDevelop;
using CommonDevelop.Operator;
using CommonDevelop.Scene;
using ManageDto;
using ManageService;

namespace WebAdmin
{
    /// <summary>
    /// 依赖项代理
    /// </summary>
    public class OperatorGetData : IOperatorGetData
    {
        private readonly IUserService _UserService;
        private readonly ILogService _LogService;
        private readonly IJwtFactory _jwtFactory;
        private readonly IPermissionManager _manager;

        /// <summary>
        /// 构造
        /// </summary>
        public OperatorGetData(IUserService UserService,
            ILogService LogService,
            IJwtFactory jwtFactory,
            IPermissionManager manager)
        {
            this._UserService = UserService;
            this._LogService = LogService;
            this._jwtFactory = jwtFactory;
            this._manager = manager;
        }

        public UserInfo CheckLogin(string account, string password, out string errors)
        {
            var Vdto = this._UserService.CheckLogin(account, password).Outcome(a => a);
            errors = Vdto.Errors;
            UserInfo userInfo = this.MakeUserInfo(Vdto.result);
            if (userInfo != null)
                return userInfo;
            else
            {
                errors = "用户账户没有取到相关数据";
                return null;
            }
        }

        public UserInfo GetUserInfo(string userID, out string error)
        {
            error = null;
            var Dto = this._UserService.GetUserDto(userID).Outcome();
            UserInfo userInfo = this.MakeUserInfo(Dto);
            if (userInfo != null)
                return userInfo;
            else
            {
                error = "用户账户没有取到相关数据";
                return null;
            }
        }

        private UserInfo MakeUserInfo(UserDto Dto)
        {
            if (Dto != null)
            {
                UserInfo userInfo = Dto.MapTo<UserInfo>();
                userInfo.Token = Dto.Token;
                userInfo.Secretkey = Dto.Secretkey;
                userInfo.BusinessID = Dto.BusinessID;
                userInfo.IP = OperatorProvider.Provider.GetIP();
                userInfo.DomainPath = GlobalData.DomainPath;
                //填充配置权限                
                userInfo.Power = this._manager.GetPowerByUId(Dto.UserId);
                userInfo.MyMenu = this._manager.GetSysMenuByUId(Dto.UserId);

                return userInfo;
            }
            else
                return null;
        }

        public UserInfo UserInfoWith(UserInfo UI)
        {
            if (UI == null)
                return UI;

            if (string.IsNullOrWhiteSpace(UI.JWT_Token))
                UI.JWT_Token = this._jwtFactory.GenerateJWT(UI.Account, UI.Token, UI.UserId, UI.BusinessID).Result;

            return UI;
        }

        public void WriteLog(LogModel model)
        {
            this._LogService.Add(model);
        }
    }
}
